package com.aierkeji.call.cms.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.springframework.http.HttpStatus;

import com.aierkeji.call.cms.entity.AkjCallUser;
import com.aierkeji.call.cms.util.GsonUtils;
import com.aierkeji.call.cms.util.ResultMapHelper;

public class ShiroPermsFilter extends PermissionsAuthorizationFilter {

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        AkjCallUser User = (AkjCallUser) httpServletRequest.getSession().getAttribute("loginUser");


        if (null == User) {
            //是ajax请求
            httpServletResponse.setContentType("text/json;charset=UTF-8");//设置响应头
            //返回json 数据，告知无权限
            httpServletResponse.getWriter().write(GsonUtils.parseToJson(ResultMapHelper.nonLogin()));
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }

    /**
     * shiro认证perms资源失败后回调方法
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //获取当前用户
        Subject subject = this.getSubject(httpServletRequest, httpServletResponse);
        //判断是否已经认证
        String requestedWith = httpServletRequest.getHeader("X-Requested-With");

        if (subject.getPrincipal() == null) {
            //是ajax请求
            httpServletResponse.setContentType("text/json;charset=UTF-8");//设置响应头
            //返回json 数据，告知无权限
            httpServletResponse.getWriter().write(GsonUtils.parseToJson(ResultMapHelper.nonLogin()));
        } else {
            httpServletResponse.setContentType("text/json;charset=UTF-8");//设置响应头
            //返回json 数据，告知无权限
            httpServletResponse.getWriter().write(GsonUtils.parseToJson(ResultMapHelper.permissionDenied()));
        }
        return false;
    }
}